package org.tuoren.official.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.tuoren.common.core.domain.R;
import org.tuoren.common.core.exception.ServiceException;
import org.tuoren.common.core.utils.MapstructUtils;
import org.tuoren.common.mybatis.core.page.TableDataInfo;
import org.tuoren.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.tuoren.official.constant.ConstantUtils;
import org.tuoren.official.domain.Department;
import org.tuoren.official.domain.Product;
import org.tuoren.official.domain.bo.ProductLineBo;
import org.tuoren.official.domain.vo.ProductLineVo;
import org.tuoren.official.domain.ProductLine;
import org.tuoren.official.mapper.DepartmentMapper;
import org.tuoren.official.mapper.ProductLineMapper;
import org.tuoren.official.mapper.ProductMapper;
import org.tuoren.official.service.IProductLineService;
import software.amazon.awssdk.utils.CollectionUtils;

import java.util.*;

/**
 * 产品线/领域Service业务层处理
 *
 * @author wl
 * @date 2024-11-26
 */
@RequiredArgsConstructor
@Service
public class ProductLineServiceImpl implements IProductLineService {

    private final ProductLineMapper baseMapper;
    private final DepartmentMapper departmentMapper;
    private final ProductMapper productMapper;

    /**
     * 查询产品线/领域
     *
     * @param id 主键
     * @return 产品线/领域
     */
    @Override
    public ProductLineVo queryById(Long id) {
        ProductLineVo productLineVo = baseMapper.selectVoById(id);
        if (productLineVo != null && StringUtils.isNotBlank(productLineVo.getTypeId())) {
            String[] typeIds = productLineVo.getTypeId().split(ConstantUtils.SEPARATOR_DB);
            List<Long> typeList = new ArrayList<>();
            for (String typeId : typeIds) {
                try {
                    Department department = departmentMapper.selectById(Long.valueOf(typeId));
                    if (department != null) {
                        typeList.add(Long.parseLong(typeId.trim()));
                    }
                } catch (NumberFormatException e) {
                    // 处理异常情况，如日志记录或忽略无效的typeId
                    // 可以根据业务需求选择处理方式
                }
            }
            productLineVo.setTypeList(typeList);
        }
        return productLineVo;
    }

    /**
     * 分页查询产品线/领域列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品线/领域分页列表
     */
    @Override
    public TableDataInfo<ProductLineVo> queryPageList(ProductLineBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ProductLine> lqw = buildQueryWrapper(bo);
        Page<ProductLineVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //将result的type_id字段转换为type_name字段,同样以逗号分隔
        result.getRecords().forEach(item -> {
            String typeId = item.getTypeId();
            String[] typeIds = typeId.split(ConstantUtils.SEPARATOR_DB);
            String typeName = "";
            for (String id : typeIds) {
                Department department = departmentMapper.selectById(Long.valueOf(id));
                if (department != null) {
                    typeName += department.getName() + ConstantUtils.SEPARATOR;
                }
            }
            item.setTypeName(typeName == "" ? "" : typeName.substring(0, typeName.length() - 1));
        });
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<ProductLineVo> frontList(ProductLineBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ProductLine> lqw = buildQueryWrapper(bo);
        Page<ProductLineVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
    /**
     * 查询符合条件的产品线/领域列表
     *
     * @param bo 查询条件
     * @return 产品线/领域列表
     */
    @Override
    public List<ProductLineVo> queryList(ProductLineBo bo) {
        LambdaQueryWrapper<ProductLine> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ProductLine> buildQueryWrapper(ProductLineBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ProductLine> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), ProductLine::getName, bo.getName());
        if (StringUtils.isNotBlank(bo.getTypeId())) {
            lqw.apply("find_in_set ('" + bo.getTypeId() + "',type_id)");
        }
        lqw.eq(StringUtils.isNotBlank(bo.getBannerUrl()), ProductLine::getBannerUrl, bo.getBannerUrl());
        lqw.orderByAsc(ProductLine::getOrderNum);
        return lqw;
    }

    /**
     * 新增产品线/领域
     *
     * @param bo 产品线/领域
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ProductLineBo bo) {
        ProductLine add = MapstructUtils.convert(bo, ProductLine.class);
        validEntityBeforeSave(add);
        add.setTypeId(String.join(ConstantUtils.SEPARATOR_DB, bo.getTypeList()));
        bo.setTypeList(List.of(bo.getTypeId().split(ConstantUtils.SEPARATOR_DB)));
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改产品线/领域
     *
     * @param bo 产品线/领域
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProductLineBo bo) {
        ProductLine update = MapstructUtils.convert(bo, ProductLine.class);
        validEntityBeforeSave(update);
        update.setTypeId(String.join(ConstantUtils.SEPARATOR_DB, bo.getTypeList()));
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ProductLine entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品线/领域信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public R deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (Long id : ids) {
            List<Product> products = productMapper.selectList(Wrappers.lambdaQuery(Product.class).eq(Product::getTypeId, id));
            if (CollectionUtil.isNotEmpty(products)) {
                return R.fail("产品线名称为 " + baseMapper.selectVoById(id).getName() + " 的产品线下有产品，请先删除产品后再删除产品线");
            }
        }
        return R.ok(baseMapper.deleteByIds(ids) > 0);
    }

}
